package io.bdmc.modules.bss.controller;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import io.bdmc.common.annotation.SysLog;
import io.bdmc.common.utils.LatLngUtil;
import io.bdmc.common.utils.MyMap;
import io.bdmc.common.utils.MyPage;
import io.bdmc.common.utils.R;
import io.bdmc.common.utils.RedisUtils;
import io.bdmc.modules.bss.entity.BarDev;
import io.bdmc.modules.bss.entity.BarRealtime;
import io.bdmc.modules.bss.entity.BarSending;
import io.bdmc.modules.bss.model.BarDevParam;
import io.bdmc.modules.bss.model.LatLngParam;
import io.bdmc.modules.bss.service.BarDevService;
import io.bdmc.modules.bss.service.BarRealtimeService;
import io.bdmc.modules.bss.service.BarSendingService;
import io.bdmc.modules.sys.controller.AbstractController;


/**
 * <p>
 * 护栏监控设备表 前端控制器
 * </p>
 *
 * @author HuangLu
 * @since 2019-01-07
 */
@RestController
@RequestMapping("/bss/dev")
public class BarDevController extends AbstractController {

    @Autowired
	private BarDevService devSvs;

	@Autowired
	private RedisUtils redisSvs;

	@Autowired
	private BarSendingService sendSvs;

	@Autowired
	private BarRealtimeService realSvs;


	@RequestMapping("/list")
	//@RequiresPermissions("sys:dev:list")
	public R list(BarDevParam params){
		//查询列表数据
        MyPage<BarDev> myPage = new MyPage<BarDev>(params.getCurrent(), params.getSize());
		MyPage<BarDev> map = devSvs.mySelectPage(myPage, params);
		
		return R.ok().putData(MyMap.ok(map.getRecords(), map.getTotal()));
    }
	
	@RequestMapping("/devs")
	//@RequiresPermissions("bss:dev:delete")
	public R devs(String code1,String code2,String code3) {
		QueryWrapper<BarDev> w = new QueryWrapper<BarDev>();
		w.isNotNull("install_code");
		if(!StringUtils.isEmpty(code1)){
			w.like("code1", code1);
			
		}
		if(!StringUtils.isEmpty(code2)){
			w.like("code2", code2);
		}
		if(!StringUtils.isEmpty(code3)){
			w.like("code3", code3);
		}
		return R.ok().putData(devSvs.list(w));
	}
    
    /**
	 * 保存设备
	 */
	@SysLog("保存设备")
	@RequestMapping("/save")
	//@RequiresPermissions("bss:dev:save")
	public R save(@RequestBody BarDev dev){
		dev.setCreateUser(getUserId());
		devSvs.save(dev);
		return R.ok();
    }

     /**
	 * 修改设备
	 */
	@SysLog("修改设备")
	@RequestMapping("/update")
	//@RequiresPermissions("bss:dev:save")
	public R update(@RequestBody BarDev dev){
		devSvs.saveOrUpdate(dev);		
		return R.ok();
    }
	
	@SysLog("设置位号编码")
	@RequestMapping("/install")
	//@RequiresPermissions("bss:dev:save")
	public R install(@RequestBody BarDev dev){
		//BarDev dbdev = devSvs.getById(dev.getDevId());
		QueryWrapper<BarDev> w1 = new QueryWrapper<BarDev>().eq("sim", dev.getSim());
		BarDev dbdev = devSvs.getOne(w1);
		dbdev.setInstallCode(dev.getInstallCode());
		dbdev.setCode1(dev.getCode1());
		dbdev.setCode2(dev.getCode2());
		dbdev.setCode3(dev.getCode3());
		dbdev.setInstallRoad(dev.getInstallRoad());
		devSvs.saveOrUpdate(dbdev);	

		QueryWrapper<BarRealtime> w2 = new QueryWrapper<BarRealtime>().eq("sim", dev.getSim());
		BarRealtime r = realSvs.getOne(w2);
		if(r!=null){
			r.setDevId(dbdev.getDevId());
			realSvs.saveOrUpdate(r);
		}
		return R.ok();
	}
	
	//@SysLog("批量设置位号编码")
	
	@RequestMapping("/install_batch")
	public R installBatch(@RequestBody List<Map<String,String>> param){
		List<BarDev> list = new ArrayList<>();
		for (Map<String,String> m : param) {
			 //修改值
			 BarDev dev = devSvs.getById(Long.valueOf(m.get("devId")));
			 dev.setInstallCode(m.get("installCode"));
			 dev.setInstallRoad(m.get("installRoad"));
			 dev.setCode1(m.get("code1"));
			 dev.setCode2(m.get("code2"));
			 dev.setCode3(m.get("code3"));
			 dev.setInstallDate(LocalDateTime.now());
			 list.add(dev);
		}
		boolean b = devSvs.updateBatchById(list);
		return R.trueOfFalse(b);
    }

    /**
	 * 删除
	 */
	@RequestMapping("/delete")
	//@RequiresPermissions("bss:dev:delete")
	public R delete(@RequestBody long devId) {
		if(devId>0)
		devSvs.removeById(devId);

		return R.ok();
	}

	    /**
	 * 重置原始经纬度
	 */
	@RequestMapping("/resetloc")
	//@RequiresPermissions("bss:dev:resetloc")
	public R resetLoc(@RequestBody long devId) {
		BarDev dev = devSvs.getById(devId);
		if(dev==null){
			return R.error(-1,"参数错误");
		}
		dev.setLat("");
		dev.setLng("");
		boolean b = devSvs.updateById(dev);
		return R.trueOfFalse(b);
	}

	@RequestMapping("/send")
	@RequiresPermissions("bss:dev:send")
	public R send(@RequestBody List<BarSending> sendings) {		
		if(sendings.size()<1){
			return R.error("参数错误");
		}
		LocalDateTime now = LocalDateTime.now();
		Long second = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));//时间戳
		String key = "DownSend"+second;//redis set name
		for (BarSending item : sendings) {
			item.setCreateDate(now);
			item.setSendStatus(0);
			item.setCacheName(key);
		}
		sendSvs.saveBatch(sendings);
		Long count = redisSvs.batchSetAdd(key, sendings.toArray());
		if(count>0){
			redisSvs.publisher("DownSendDeviceChannel_FG",key);
		}
		return R.ok();
	}




	// @RequestMapping("/test")
	// //@RequiresPermissions("bss:dev:delete")
	// public R test1() {
	// 	redisSvs.set("key", "huanglu1212");
    //     String s =  redisSvs.get("key");
	
	// 	return R.ok(s);
	// }

	// @RequestMapping("import")
    // //@ApiOperation(value = "导入Excel",notes = "将数据以Excel的形式导入到数据库中")
    // public R importExcel(@RequestParam("file") MultipartFile file) throws Exception {
    //     //获取用户上传表格的地址，执行完程序后表格将会删除，避免占用内存
    //     //根据地址和文件名准确获取用户上传的表格
    //     //File tempFile = new File(file.getInputStream());
    //     try {
    //         //将MultipartFile转换为File类型
	// 	   // file.transferTo(tempFile);
	// 	   String fileName = file.getOriginalFilename();
	// 	   String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
	// 	   InputStream in = file.getInputStream();
    //         List<Map<String,String>> dataList = ExcelImport.read(in,suffix);
	// 	   BarDev dev = new BarDev();
	// 	   List<BarDev> list = new ArrayList<BarDev>();
    //         for (int i = 0; i < dataList.size(); i++) {
	// 			if(StringUtils.isEmpty(dataList.get(i).get("sim"))){
	// 				continue;
	// 			}
	// 			String simNum = dataList.get(i).get("sim").toString();
	// 			dev = (BarDev)dev.clone();
	// 			dev.setSim(simNum);
	// 			dev.setDeptId(getDeptId());
	// 			dev.setCreateTime(new Date());
	// 			dev.setCreateUser(getUserId());
	// 			list.add(dev);
    //         }


	// 		Boolean re = devSvs.saveBatch(list);
	// 		return R.ok(re.toString());
    //     } catch (Exception e) {
    //         //tempFile.delete();
    //         throw new Exception("批量录入用户失败，请检查表格中的数据是否和数据库中的数据冲突！");
    //     }
       
    // }

}

